<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="文档名" v-model="listQuery.document_name">
      </el-input>
      <el-select clearable class="filter-item" style="width: 150px" v-model="listQuery.folder" placeholder="文件夹" >
        <el-option v-for="item in folderOption" :key="item.id" :label="item.name" :value="item.id">
        </el-option>
      </el-select>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">{{$t('table.search')}}</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary">上传</el-button>
    </div>

    <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row
      style="width: 100%">
      <el-table-column label="文档名"  width="300px" >
        <template slot-scope="scope">
          <span>{{scope.row.document_name }}</span>
        </template>
      </el-table-column>
      <el-table-column  align="center" label="文件夹" min-width="120px">
        <template slot-scope="scope">
          <span>{{scope.row.folder_id | listFolderValFilter}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="大小" min-width="150px">
        <template slot-scope="scope">
          <span>{{scope.row.document_size | sizefilter}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="上传日期" width="200px" >
        <template slot-scope="scope">
          <span>{{scope.row.create_date | timeFilter('{y}-{m}-{d} {h}:{i}:{s}')}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="上传者" min-width="120px">
        <template slot-scope="scope">
          <span>{{scope.row.create_name}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" :label="$t('table.actions')"  class-name="small-padding fixed-width" min-width="100px">
        <template slot-scope="scope">
          <!-- <a :href="scope.row.document_url" :download="scope.row.document_name">下载</a> -->
          <el-button type="primary" size="mini" @click="download(scope.row)">下载</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog title="文件上传" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="70px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="文件夹" prop="department_code">
          <el-select clearable class="filter-item" style="width: 150px" v-model="temp.folder" placeholder="请选择" >
            <el-option v-for="item in folderOption" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文件上传" prop="department_type">
          <el-upload
              class="upload-demo"
              action="/api/list/file"
              :data="temp"
              :headers="headers"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-upload="beforeUpload"
              :before-remove="beforeRemove"
              :on-success="uploadSuccess"
              :limit="1"
              :on-exceed="handleExceed"
              :file-list="fileList">
              <el-button icon='el-icon-upload' size="small" plain>上传</el-button>
              <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
            </el-upload> 
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
import API from '@/utils/backend_api'
import waves from '@/directive/waves'
import Static_Data from '@/data/index'
import { getToken } from '@/utils/auth'
export default {
  name: 'list',
  components: { },
  directives: {
    waves
  },
  data() {
    return {
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      folderOption: Static_Data.list_folder,
      tableKey: 0,
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        document_name: '',
        folder: '',
        sort: '-create_date'
      },
      temp: {
        folder: ''
      },
      dialogFormVisible: false,
      rules: {
      },
      fileList: [],
      headers: {
        Authorization: getToken(),
        smail: '*_~'
      }
    }
  },
  filters: {
    sizefilter: function(limit) {
      let size = ''
      if (limit === 0 || limit === '0') {
        size = '0B'
      } else if (limit < 0.1 * 1024) {
        // 如果小于0.1KB转化成B
        size = limit.toFixed(2) + 'B'
      } else if (limit < 0.1 * 1024 * 1024) {
        // 如果小于0.1MB转化成KB
        size = (limit / 1024).toFixed(2) + 'KB'
      } else if (limit < 0.1 * 1024 * 1024 * 1024) {
        // 如果小于0.1GB转化成MB
        size = (limit / (1024 * 1024)).toFixed(2) + 'MB'
      } else {
        size = (limit / (1024 * 1024 * 1024)).toFixed(2) + 'GB'
      }
      const sizestr = size + ''
      const len = sizestr.indexOf('\.')
      const dec = sizestr.substr(len + 1, 2)
      if (dec === '00') {
        return sizestr.substring(0, len) + sizestr.substr(len + 3, 2)
      }
      return sizestr
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      API.list.all(this.listQuery).then(response => {
        console.log(response)
        this.list = response.data
        if (response.headers && response.headers['x-total-count']) {
          this.total = Number(response.headers['x-total-count'])
        }
        this.listLoading = false
      })
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      console.log(file)
    },
    handleExceed(files, fileList) {
      this.$message.warning('当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件')
    },
    beforeRemove(file, fileList) {
      return this.$confirm('确定移除 ${ file.name }?')
    },
    uploadSuccess(response, file, fileList) {
      this.list.unshift(response)
    },
    beforeUpload(file) {
      if (this.temp && this.temp.folder && this.temp.folder !== '') {
        return true
      } else {
        this.$message.warning('文件夹不能为空')
        return false
      }
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    resetTemp() {
      this.temp = {
        folder: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // createData() {
    //   this.$refs['dataForm'].validate((valid) => {
    //     if (valid) {
    //       API.department.add(this.temp).then((response) => {
    //         console.log('add:')
    //         console.log(response)
    //         this.list.unshift(response.data)
    //         this.dialogFormVisible = false
    //         this.$notify({
    //           title: '成功',
    //           message: '创建成功',
    //           type: 'success',
    //           duration: 2000
    //         })
    //       })
    //     }
    //   })
    // },
    download(row) {
      API.list.get(row.id).then(response => {
        var fileDownload = require('downloadjs')
        fileDownload(response.data, row.document_name)
      })
    }
  }
}
</script>
